<%@ page pageEncoding="UTF-8"%>
<%!
	// 获取推送用户
	public Map<String, Map<String, String>> getUsers(List<String> patients, int hospital) {
		Map<String,Map<String, String>> users = new HashMap<String, Map<String, String>>();
		String patient = "-99";
		Map<String, String> p = new HashMap<String, String>();
		for (int i = 0; i < patients.size(); i++) {
			patient += ("," + patients.get(i));
			p.put(patients.get(i), patients.get(i));
		}
		// Android用户
		users.put("Android", p);
		// iOS用户
		List<Map<String, String>> iOS = QBuilder.db("basedb").queryHql("select new map(de.token as token,  CONCAT(us.id, '') as id) from User as us, DeviceToken as de where us.id in (" + patient + ") and us.status = " + STATUS_ENABLE + " and de.uid = us.id order by de.mTime desc"); //取最新修改的时间
		users.put("iOS", remove(iOS));
		// 微信用户
		List<Map<String, String>> wechat = QBuilder.db("basedb").queryHql("select new map(token as token, CONCAT(uid, '') as id) from Token where uid in (" + patient + ") and expireIn = -1 order by cTime desc");
		users.put("wechat", remove(wechat));
		return users;
	}

	// 去除重复用户
	public Map<String, String> remove(List<Map<String, String>> list) {
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < list.size(); i++) {
			Map<String, String> temp = list.get(i);
			String id = temp.get("id");
			if (map.get(id) == null)
				map.put(id, temp.get("token"));
		}
		return map;
	}

	// 推送Android
	public void pushAndroid(List<String> patients, int hospital, Map<String, Map<String, String>> pushContent) {
		push(false, patients, hospital, pushContent, "Android");
	}

	// 推送iOS
	public void pushIOS(boolean isDev,List<String> patients, int hospital, Map<String, Map<String, String>> pushContent) {
		push(isDev, patients, hospital, pushContent, "iOS");
	}

	// 推送微信
	public void pushWechat(List<String> patients, int hospital, Map<String, Map<String, String>> pushContent) {
		push(false, patients, hospital, pushContent, "wechat");
	}

	// 推送所有
	public void pushAll(boolean isDev, List<String> patients, int hospital, Map<String, Map<String, String>> pushContent) {
		push(isDev, patients, hospital, pushContent, "All");
	}

	// 推送
	public void push(final boolean isDev, List<String> patients, final int hospital, Map<String, Map<String, String>> pushContent, final String type) {
		System.out.println("推送isDev："+isDev);
		final Map<String, Map<String, String>> map = getUsers(patients, hospital);
		for (int i = 0; i < patients.size(); i ++) {
			final String patientUid = patients.get(i);
			final Map<String, String> content = pushContent.get(patientUid);
			if (content == null)
				continue;
			new Thread(new Runnable() {

				@Override
				public void run() {
					HashMap<String, Object> param = new HashMap<String, Object>();
					if ("All".equals(type) || "iOS".equals(type)) {
						// 推送iOS
						List<String> tokens = new ArrayList<String>();
						String token = map.get("iOS").get(patientUid);
						
						if (token != null) {
							tokens.add(token);
							param.put("uid", patientUid);
							param.put("id",  content.get("id"));
							param.put("hospital", hospital);
							param.put("app_type", content.get("app_type"));
							param.put("alert",  content.get("title"));
							param.put("tokens", tokens);
							param.put("type", content.get("category"));
							if ("home".equals(Tools.getDesc(content.get("act")))) {
								param.put("custom", Tools.getDesc(content.get("custom")));
							}
							param.put("sender", content.get("sender"));
							if (isDev)
								PushUtil.pushDev(param);
							else
								PushUtil.push(param);
						}
					}
					if ("All".equals(type) || "Android".equals(type)) {
						// 推送Android
						com.tencent.xinge.XingeApp push = new com.tencent.xinge.XingeApp(Tools.getInt(content.get("appid")), content.get("appsecret"));
						com.tencent.xinge.Message msgAndroid = new com.tencent.xinge.Message();
						msgAndroid.setType(com.tencent.xinge.Message.TYPE_NOTIFICATION);
						com.tencent.xinge.Style style = new com.tencent.xinge.Style(0, 1, 1, 1, 0, 1, 1, 0);
						msgAndroid.setStyle(style);
						com.tencent.xinge.ClickAction action = new com.tencent.xinge.ClickAction();
						action.setActionType(com.tencent.xinge.ClickAction.TYPE_ACTIVITY);
						action.setActivity(content.get("activity"));
						msgAndroid.setAction(action);
						msgAndroid.setTitle(content.get("title"));
						msgAndroid.setContent(content.get("content"));
						param.put("uid", patientUid);
						param.put("id",  content.get("id"));
						param.put("hospital", hospital);
						param.put("app_type", content.get("app_type"));
						param.put("alert",  content.get("title"));
						param.put("type", content.get("category"));
						if ("home".equals(Tools.getDesc(content.get("act")))) {
							param.put("custom", Tools.getDesc(content.get("custom")));
							msgAndroid.setMultiPkg(1);
						}
						param.put("sender", content.get("sender"));
						msgAndroid.setCustom(param);
						List<String> tokens = new ArrayList<String>();
						tokens.add(patientUid);
						push.pushAccountList(0, tokens, msgAndroid);
					}
					if ("All".equals(type) || "wechat".equals(type)) {
						// 推送微信
						Map<String, String> text = new HashMap<String, String>();
						text.put("first", content.get("title"));
						text.put("keyword1", content.get("keyword1"));
						text.put("keyword2", content.get("keyword2"));
						text.put("keyword3", content.get("keyword3"));
						text.put("remark", content.get("remark"));
						param.clear();
						param.put("data", makeContent(text));
						param.put("touser", map.get("wechat").get(patientUid));
						param.put("template_id", content.get("template_id"));
						param.put("url", content.get("url"));
						template(GsonUtil.toJson(param), hospital);
					}
				}
			}).start();
		}

	}

	// 微信模板信息生成
	public Map<String, Object> makeContent(Map<String, String>... maps) {
		Map<String, Object> model = new HashMap<String, Object>(); // 最后的模板
		Map<String, String> colors = new HashMap<String, String>(); // 放入颜色
		if (maps == null || maps.length < 1 || maps[0] == null)
			return model;
		if (maps.length > 2) {
			colors = maps[1];
		}
		Set<Entry<String, String>> keySet = maps[0].entrySet();
		String color = "#173177";
		for (Entry<String, String> entry : keySet) {
			String key = entry.getKey();
			String value = entry.getValue();
			Map<String, String> map = new HashMap<String, String>();
			map.put("value", value);
			map.put("color", colors.get(key) == null ? color : colors.get(key));
			model.put(key, map);
		}
		return model;
	}

	public Map getHospital(int hospital){
		// 医院信息
		List list = QBuilder.db("basedb").queryHql("from hospital where hospital =" + hospital);
		String json = "{}";
		if (list.size () > 0) {
			Map map = (Map)list.get(0);
			json = map.get("json") + "";
		}
		Map result = GsonUtil.fromJson(json, new TypeToken<HashMap>(){});
		return result;
	}

	// 获取公众号token
	public String token(int hospital) {
		String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;//获得该公众号的token
		String tokenJson = HttpUtil.get(url);//拿到这个公众号对应的token
	    HashMap tokeMap = GsonUtil.fromJson(tokenJson, new TypeToken<HashMap>(){});
	    String token =  Tools.getDesc(tokeMap.get("access_token"), "");
		return token;
	}

	// 推送微信
	public Message template(String message, int hospital){
		Message msg = new Message();
		try{
			String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token(hospital);
			String html = HttpUtil.soap(url, message, "UTF-8");
			HashMap result = GsonUtil.fromJson(html, new TypeToken<HashMap>(){});
			return new Message(((Double)result.get("errcode")).intValue(), (String)result.get("errmsg"));
		} catch(Exception e) {
			e.printStackTrace();
			setErrcode(msg, SEND_ERROR);
		}
		return msg;
	}

	public boolean isDev(Input input) {
		HttpServletRequest request = input.getRequest();
		String server = request.getServerName();
		if ("192.168.2.11".equals(server)) {
			return true;
		} else if ("apieee.tianxiabuyi.com".equals(server)) {
			return false;
		} else if ("demoapi.tianxiabuyi.com".equals(server)) {
			return true;
		}
		return true;
	}
%>
